define(['moment'], function () {
    return ['$scope', '$rootScope', '$filter', '$stateParams', '$mdDialog', 'config', 'MMWService', '$calculater', '$timeout', '$mddProvider',
        function ($scope, $rootScope, $filter, $stateParams, $mdDialog, config, $MMWService, $calculater, $timeout, $mddProvider) {
            
            // 20220422 modify by Alan for #102658	 :  異常資料警示介面
            // $timer變數
            var light_dog = {};
            
            $scope._event = {
                item_no: {
                    click: () => {
                        $scope.loadItemNo();
                    }
                },
                wo_no: {
                    click: () => {
                        $scope.loadWoNo();
                    }
                },
            	// 20230328 modify by Alan for M#0122582 - 修正開關
                'open_off_one': {
                    click: (model, args) => {
                        $scope.ClickDoFlag();
                        $scope.open_off_one = ($scope.do_flag != 0).toString();
                    }
                },
                'open_off_two': {
                    click: (model, args) => {
                        $scope.decideChange();
                        $scope.open_off_two = ($scope.changeNumOrNot != 1).toString();
                    }
                }
            }
            //_fn['confirm'].click('confirm');
            $scope._fn = {
                search: {
                    click: () => {
                        $scope.search();
                    }
                },
                'plot_info_detail.btn': {
                    click: (btn, str_btn, object) => {
                        item = object.eventScope;
                        $scope.callB0225(item);
                    }
                },
                'selectedList.selectNo': {
                    click: (btn, str_btn, object) => {
                        item = object.eventScope;
                        $scope.serialNoCheck(item);
                    }
                },
                'confirm': {
                    click: () => {
                        $scope.confirm();
                    }
                }

            }
            $scope.init = function () {
                // $scope.open_off_one = ($scope.do_flag == 0).toString();
                // $scope.open_off_two = ($scope.changeNumOrNot == 1).toString();
                $MMWService.PNIGList = {};
                $scope.warehouseInfo = {
                    type: '', product_warehouse: '', storage: '',
                    plot_info_detail: [],
                    wo_no: '', item_no: '', plot_no: '', erp_doc_type: ''
                };

                $scope.type = '0';
                $scope.selectedList = [];

                $scope.warehouseInfo.item_no = '';
                $scope.warehouseInfo.item_name = '';
                $scope.warehouseInfo.wo_no = '';

                $scope.warehouseInfo.select_type = 3;

                $scope.list_filter = {};
                $scope.filterSH = {};
                $scope.feedback_type = [];
                // 20230720 modify by Alan for #141120	 : 修正制成完工預設值為0配合3.4，並映射到open_off_one
                $scope.do_flag = 0; // 制成完工
                $scope.open_off_one = ($scope.do_flag != 0).toString();
                $scope.changeNumOrNot = 0;
                $scope.do_print= 0;
              
                // 20221004 modify by Alan for #112079 : FQC系統參數
                // 01：SMES 
                // 10：ISPC 
                // 20：IMES 
                // 11：SMES+ISPC(sQMS)
                // 檢查是否有購買sMES，就是判斷此參數為11時，非11都走原畫面
                // 20221109 modify by Alan for #112079 : sQMS版本判斷，sQMS需要再3.0版本後才支援FQC
                var isBoughtQMS = (+config.cache.sys_parameter.ProductSCode === 11);
                var isSupportQMS = config.cache.sys_parameter.QMSVersion && config.cache.sys_parameter.QMSVersion.split('.')[0] > 2;
                $scope.sQMSEnable = isBoughtQMS && isSupportQMS;                
                // 預設入庫需FQC
                $scope.defaultStockInNeedFQC = (+config.cache.sys_parameter.DefaultStockInNeedFQC === 1);  
                // 20230303 modify by Alan for#: module_setting卡控
                $scope.PTC_ASC = config.cache.module_setting.PTC_ASC;
                //20210419 Modify by德義家興for#91013: [标准][DEV][行业议题]机加工-CNC良品工单汇总显示
                $scope.unselected_sum = 0; //未選合計
                $scope.selected_sum = 0; //已選合計
                
                // 20220422 modify by Alan for #110729 : 入庫異常按鈕開關控制
                $scope.isStorageExceptionDisabled = true;
                // 背景更新取得燈號
                    $scope.dynamicFormLoaded = () => { 
                    getLight(function(feedback, isShowLoading){
                        light_dog = $timeout(function(){
                            getLight(feedback, false);
                        }, config.setting.RefreshTime * 1000);
                    }, true);
                }
                //20220610 add by 翰鴻 for M#108133
                $scope.ERP_Name = '';
            };

            $scope.back = function () {
                $scope.$root.hideMenu();
                $scope.$root.changeProgram('home', true);
            };

            // 20220422 modify by Alan for #102658	 :  異常資料警示介面
            // 退出時停止監聽燈號
            $scope.final = function(callback){
                $timeout.cancel(light_dog);

                if(typeof callback === 'function')
                    callback();
            }

            //20170505 modify by Dustdusk for 入庫查詢可以不用輸入條件
            $scope.search = function (research) {
                var content = {
                    wo_no: $scope.warehouseInfo.wo_no,
                    item_no: $scope.warehouseInfo.item_no,
                    type: $scope.type,
                    do_flag:$scope.do_flag
                };
                warehousePlotInfoGet(content, function (response) {
                    $scope.list_filter = {};
                    $scope.filterSH = {};
                    if(response && response.length > 0){
                        //response.forEach(function(item){
                        //    //20210831 add by John for M#97202: 配合後端調整，一律以mo_stockinlotno取代入庫批次號
                        //    item.storage_plot = item.mo_stockinlotno;
                        //    $scope.selectedList.forEach(function(select_item){
                        //        if(item.wo_no === select_item.wo_no && item.plot_no === select_item.plot_no && item.item_name === select_item.item_name){
                        //            item.qty = (+select_item.qty);
                        //            item.storage_qty = (+select_item.storage_qty)
                        //            item.disconnect = true;
                        //            if(!item.qty){//如果item.qty減完是零，則刪除此列
                        //                response.splice(response.indexOf(item),1)
                        //            }
                        //        }
                        //    });
                        //});
                        // 20220329 modify by chenshibo for#109569：选中多笔到下方后，再查询显示异常
                        for (i = response.length - 1; i >= 0; i--) {
                            //20210831 add by John for M#97202: 配合後端調整，一律以mo_stockinlotno取代入庫批次號
                            response[i].storage_plot = response[i].mo_stockinlotno;
                            // 20221007 modify by Alan for #112097: 保存qty及FinalQTY協助後續判斷
                            response[i].ori_qty = response[i].qty;
                            response[i].ori_FinalQTY = response[i].FinalQTY;
                            response[i].storage_qty = 0;
                            for (var j = 0; j < $scope.selectedList.length; j++) {
                                if (response[i].wo_no === $scope.selectedList[j].wo_no && response[i].plot_no === $scope.selectedList[j].plot_no && response[i].item_name === $scope.selectedList[j].item_name) {
                                    response[i].qty = (+$scope.selectedList[j].qty);
                                    response[i].storage_qty = (+$scope.selectedList[j].storage_qty);
                                    response[i].disconnect = true;
                                    // 2022-10-13 #0112097 FQC 不移除此列，僅調整數量 start
                                    response[i].FinalQTY = (+$scope.selectedList[j].FinalQTY);
                                    // if (!response[i].qty) {//如果item.qty減完是零，則刪除此列
                                    //     response.splice(response.indexOf(response[i]), 1);
                                    //     break;
                                    // }
                                    // 2022-10-13 #0112097 FQC 不移除此列，僅調整數量 end
                                }
                            };
                        };
                        $scope.warehouseInfo.plot_info_detail = response;
                        $scope.warehouseInfo.plot_info_detail.forEach(function (detail) {
                            detail.checked = false;
                        });
                        //20210419 Modify by德義家興for#91013: [标准][DEV][行业议题]机加工-CNC良品工单汇总显示
                        calculate_sum();
                    } else if(research !== 'research'){
                        $scope.warehouseInfo.plot_info_detail = [];
                        $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                    }
                });
            };

            $scope.ClickDoFlag = function(){
                if($scope.selectedList.length>0){
                    $scope.$root.showAlert($filter('translate')('B0401.msg.already_selected'));
                } else {
                    $scope.warehouseInfo.plot_info_detail = [];
                    $scope.selectedList = [];
                    if($scope.do_flag == 1){
                        $scope.do_flag = 0;
                        if(!config.cache.permissions || config.cache.permissions.indexOf('B0225')!=-1){
                            $scope.isB0225 = true;
                        }
                    } else {
                        $scope.do_flag = 1;
                        $scope.isB0225 = false;
                    }
                }
            };
            $scope.decideChange = function(){
                if($scope.changeNumOrNot==0){
                    $scope.changeNumOrNot=1;
                }else{
                    $scope.changeNumOrNot=0;
                }
            }
            
            // 0079818: [標準][華美][出站標籤打印][DEV]末道出站時可以選擇以聯副產品打印標籤和入庫
            $scope.printChange = function(){
                if($scope.do_print==0){
                    $scope.do_print=1;
                }else{
                    $scope.do_print=0;
                }
            }

            $scope.confirm = function () {
                //20220610 add by 翰鴻 for M#108133
                if ($scope.do_flag == 1 && ($scope.ERP_Name == 'T100' || $scope.ERP_Name == 'TIPTOP')) {
                    var diffList = $.grep($scope.selectedList, function (n, i) {
                        return n.item_no_OG == n.item_no
                    });
                    if (diffList.length > 0) {
                        //XXXX = 生產批號，
                        //T系列當站下線入庫單需變更產品編號，
                        //請變更生產批: XXXX入庫產品編號
                        var plot_no = diffList[0].plot_no;
                        showAlert($filter('translate')('B0401.msg.please_change_itemno', { plot_no: plot_no }));
                        return false;
                    }
                }
                //20170612 modify by Dustdusk for 新增select_type == 4(作廢)
                if($scope.warehouseInfo.select_type == 2 || $scope.warehouseInfo.select_type == 4){
                    //誤判
                    $scope.warehouseInfo.product_warehouse = '';//成品庫
                    $scope.warehouseInfo.product_warehouse_name = '';//成品庫
                    $scope.warehouseInfo.storage = ''; //儲位
                    $scope.warehouseInfo.storage_display = ''; //儲位
                    $scope.warehouseInfo.erp_doc_type = '';//ERP單別
                    warehousePlotProcess();
                } else if($scope.warehouseInfo.select_type == 3){
                    // 20200917 modify by WeiTing for M#72157 - 檢查選取的資料是否都是相同的倉庫和儲位。
                    var sameInventoryAndStorage = isCheckSameInventoryAndStorage($scope.selectedList); 
                    //報廢入庫
                    $scope.openStorage(sameInventoryAndStorage);
                } else {
                    //重工處理/讓步處理
                    $mdDialog.serviceDialog('B0213Service',{
                        plot_detail : $scope.selectedList,
                        option : $scope.warehouseInfo.select_type, //重工:0/讓步:1
                        parent : 'B0402',
                        feedback : function(){
                            //20170330 modify by megabytes for 確認存取完後清空
                              $scope.warehouseInfo.plot_info_detail = [];
                              $scope.warehouseInfo.item_no = '';
                              $scope.warehouseInfo.item_name = '';
                              $scope.warehouseInfo.wo_no = '';
                              $scope.warehouseInfo.plot_no = '';
                              $scope.selectedList = [];
                        }
                    });
                }
            };

            // 20200917 modify by WeiTing for M#72157 - 檢查選取的資料是否都是相同的倉庫和儲位。
            function isCheckSameInventoryAndStorage(selectedList){
                var checkList = {
                    inventoryNo: '', // 倉庫
                    storageSpacesNo: '', // 儲位
                    isStopInventory: false, // 不同倉庫時，停止判斷
                    isStopStorage: false // 不同儲位時，停止判斷
                };

                if(selectedList && selectedList.length > 1){
                    for(var i = 0; i < selectedList.length > 0; i++){
                        if(i < selectedList.length - 1){
                            // 檢查選取的資料的倉庫是否都相同
                            if(selectedList[i].inventoryno && !checkList.isStopInventory){
                                if(selectedList[i].inventoryno === selectedList[i+1].inventoryno){
                                    checkList.inventoryNo = selectedList[i].inventoryno;
                                } else {
                                    checkList.inventoryNo = '';
                                    checkList.isStopInventory = true;
                                }
                            } else {
                                checkList.inventoryNo = '';
                                checkList.isStopInventory = true;
                            }

                            // 檢查選取的資料的儲位是否都相同
                            if(selectedList[i].storage_spaces_no && !checkList.isStopStorage){
                                if(selectedList[i].storage_spaces_no === selectedList[i+1].storage_spaces_no){
                                    checkList.storageSpacesNo = selectedList[i].storage_spaces_no;
                                } else {
                                    checkList.storageSpacesNo = '';
                                    checkList.isStopStorage = true;
                                }
                            } else {
                                checkList.storageSpacesNo = '';
                                checkList.isStopStorage = true;
                            }
                        }
                    }
                } else {
                    if(selectedList[0].inventoryno){
                        checkList.inventoryNo = selectedList[0].inventoryno;
                    } 
                    if(selectedList[0].storage_spaces_no){
                        checkList.storageSpacesNo = selectedList[0].storage_spaces_no;
                    } 
                }

                return checkList;
            }

            //20170405 modify by megabytes for 內存外顯修改
            //20170410 modify by megabytes for 改為皆顯示no
            //20170602 modify by Dustdusk for 開窗調整
            //20170602 modify by Dustdusk for 開窗取消
            //取得產品編號
            $scope.loadItemNo = function () {
                var page_mode;
                //20170704 modify by Dustdusk for 入庫產品清單查詢優化
                if($scope.type == '0'){
                    page_mode = 18;
                } else if($scope.type == '1'){
                    page_mode = 19;
                }
                $MMWService.showQueryListPNIG({
                    page_mode: page_mode,
                    pageRecord:50,
                    key:'page_no',
                    condition: [
                        {name:$filter('translate')('common.queryList.item_c'), column_name:'B.ProductNo', query_mode:'2', value:$scope.warehouseInfo.item_no||''},
                        {name:$filter('translate')('common.queryList.item_n'), column_name:'B.ProductName', query_mode:'2', value:''}
                    ],
                    header: [
                        {label:$filter('translate')('common.queryList.item_c'), code:'page_no'},
                        {label:$filter('translate')('common.queryList.item_n'), code:'page_name'}
                    ],
                    selectCode:$scope.warehouseInfo.item_no,
                    confirm : function(selectItem){
                        $scope.warehouseInfo.item_no = selectItem.page_no;
                        $scope.warehouseInfo.item_name = selectItem.page_name;
                        $scope.warehouseInfo.wo_no = '';
                    }
                });
            };

            //取得工單編號
            //20170602 modify by Dustdusk for 拿掉一定要輸入產品編號的限制
            //20170602 modify by Dustdusk for 開窗取消
            $scope.loadWoNo = function () {
                var page_mode;
                //20170704 modify by Dustdusk for 入庫工單清單查詢優化
                if($scope.type == '0'){
                    page_mode = 20;
                } else if($scope.type == '1'){
                    page_mode = 21;
                }
                $MMWService.showQueryListPNIG({
                    page_mode: page_mode,
                    pageRecord:50,
                    condition: [
                        {name:$filter('translate')('common.queryList.wo_c'), column_name:'C.MoNo', query_mode:'2', value:$scope.warehouseInfo.wo_no}
                    ],
                    header: [
                        {label:$filter('translate')('common.queryList.wo_c'), code:'page_no'}
                    ],
                    setCondition:function(conditions){
                        if($scope.warehouseInfo.item_no && $scope.warehouseInfo.item_no != '')
                            conditions.push({column_name:'B.ProductNo', query_mode:'0', value: $scope.warehouseInfo.item_no, merge_condition_model : 'AND'});

                        return conditions;
                    },
                    selectCode:$scope.warehouseInfo.wo_no,
                    confirm : function(selectItem){
                        $scope.warehouseInfo.wo_no = selectItem.page_no;
                    }
                });
            };

            $scope.pickTarget = function () {
                var targetArray = [];
                for (var i = 0; i < $scope.warehouseInfo.plot_info_detail.length; i++) {
                    if ($scope.warehouseInfo.plot_info_detail[i].plot_no.indexOf($scope.warehouseInfo.plot_no) != -1) {
                        var target = $scope.warehouseInfo.plot_info_detail[i];
                        let repeatStorage = check_select_list_repeat(target);
                        var isOK = true;
                        
                        // 20221007 modify by Alan for #112097	 :  
                        // 当产品需要FQC时，tblinvwipinventory_semi.FinalQty >0 
                        // 最终数量大於0，则加入「最终数量」至「待出库清单中」，
                        // 则跳出错误信息
                        // 当产品不需要FQC时，tblinvwipinventory_semi.FinalQty >0 
                        // 最终数量大於0，则加入「最终数量」至「待出库清单中」；
                        // tblinvwipinventory_semi.FinalQty =0 最终数量等於0时，则加入「生产数量 Qty」至「待出库清单中」，
                        // 生产数量 Qty及 最终数量 FinalQty 都为0 时，则跳出错误信息
                        if(target.IsNeedFQC) {
                            if(+target.FinalQTY <= 0) {
                                $rootScope.showAlert($filter('translate')('B0401.msg.plot_qty_is_zero', {plot_no: target.plot_no}));
                                return;
                            } 
                        } else {
                            if(+target.FinalQTY <= 0 && +target.qty <= 0) {
                                $rootScope.showAlert($filter('translate')('B0401.msg.plot_qty_is_zero', {plot_no: target.plot_no}));
                                return;
                            } 
                        }
                        if($scope.changeNumOrNot == 1 ){
                            $scope.openNumChangebox(target,repeatStorage);
                        }else{
                            if($scope.type == 0){
                                for(var j = 0 ; j < $scope.selectedList.length ; j++){
                                    if($scope.selectedList[j].plot_no == target.plot_no && $scope.selectedList[j].qty == target.qty){
                                        //當兩者相同時更新產品資訊
                                        //$scope.selectedList[j].item_no = target.item_no;
                                        //$scope.selectedList[j].item_name = target.item_name;
                                        //$scope.selectedList[j].item_unit_no = target.item_unit_no;
                                        //$scope.selectedList[j].item_ver = target.item_ver;

                                        isOK = false;
                                        break;
                                    }
                                }
                            }else if ($scope.type == 1){
                                for(var j = 0 ; j < $scope.selectedList.length ; j++){
                                    //20180425 modify by Dustdusk for 相同生產批不同不良原因要能選擇
                                    if($scope.selectedList[j].lot_serial == target.lot_serial && $scope.selectedList[j].error_no == target.error_no){
                                        isOK = false;
                                        break;
                                    }
                                }
                            }

                            if(isOK){
                                target.checked = true;
                                target.storage_qty = target.IsNeedFQC
                                    ? target.FinalQTY
                                    : target.FinalQTY || target.qty;
                                target.qty = 0;
                                check_select_list(target,repeatStorage);
                                // $scope.selectedList.push(target);
                                targetArray.push(target);
                            }
                        }
                        //$scope.warehouseInfo.plot_info_detail.splice($scope.warehouseInfo.plot_info_detail.indexOf(target), 1);
                    }
                }

                targetArray.forEach(function(target){
                    $scope.warehouseInfo.plot_info_detail.splice($scope.warehouseInfo.plot_info_detail.indexOf(target), 1);
                })
                //20210419 Modify by德義家興for#91013: [标准][DEV][行业议题]机加工-CNC良品工单汇总显示
                calculate_sum();
            };

            //20170329 modify by megabytes for 刪除佇列部分也需要判斷是否重複問題
            $scope.returnTarget = function (index, data) {
                var searchrepeat = false;
                for(var i = 0 ; i < $scope.warehouseInfo.plot_info_detail.length ; i++){
                    if($scope.type == 0){
                        if($scope.warehouseInfo.plot_info_detail[i].plot_no == data.plot_no && $scope.warehouseInfo.plot_info_detail[i].qty == data.qty){
                            searchrepeat = true;
                            break;
                        }
                    }else if ($scope.type == 1){
                        if($scope.warehouseInfo.plot_info_detail[i].lot_serial == data.lot_serial && $scope.warehouseInfo.plot_info_detail[i].error_no == data.error_no){
                            searchrepeat = false;
                            break;
                        }
                    }
                }
                
                data.checked = !data.checked;
                // 20221007 modify by Alan for #112097	 : 依照ori_FinalQTY判斷要回寫FinalQTY還是qty
                data.qty = +data.ori_qty;
                data.FinalQTY = +data.ori_FinalQTY;
                data.storage_qty = 0;
                
                //20180425 modify by Dustdusk for 當良品入庫且刪除時要回復變更前的產品
                if($scope.type == 0 && data.joint_trigger == 'Y'){
                    data.item_no = data.old_item_no||data.item_no;
                    data.item_name = data.old_item_name||data.item_name;
                    data.item_unit_no = data.old_item_unit_no||data.item_unit_no;
                    data.item_ver = data.old_item_ver||data.item_ver;
                    delete data.joint_trigger;
                }

                if(searchrepeat){    
                    //檢查有無同一生產批
                    let origin_item_key;
                    let origin_item=false;
                    $scope.warehouseInfo.plot_info_detail.forEach(function(item,key){
                        if(data.plot_no === item.plot_no && item.wo_no === data.wo_no && item.plot_no === data.plot_no && item.item_name === data.item_name){ origin_item_key= key;origin_item=true}
                    })
                    if(origin_item){//warehouse陣列有這筆資料，可以只刪除selectedList內的這筆資料即可
                        // 20221007 modify by Alan for #112097	 : 依照ori_FinalQTY判斷要回寫FinalQTY還是qty
                        $scope.warehouseInfo.plot_info_detail[origin_item_key].qty = data.qty;
                        $scope.warehouseInfo.plot_info_detail[origin_item_key].FinalQTY = data.FinalQTY;
                        $scope.warehouseInfo.plot_info_detail[origin_item_key].storage_qty = data.storage_qty;
                        $scope.selectedList.splice(index, 1);
                    }else{
                        $scope.selectedList.splice(index, 1);
                        $scope.warehouseInfo.plot_info_detail.splice(data.warehouse_index,0,data);//把data放回warehouse陣列
                    }
                }else{
                    // 檢查有無同一生產批
                    let origin_item_key;
                    let origin_item=false;
                    $scope.warehouseInfo.plot_info_detail.forEach(function(item,key){
                        if(data.plot_no === item.plot_no && item.wo_no === data.wo_no && item.plot_no === data.plot_no && item.item_name === data.item_name){ origin_item_key = key;origin_item = true}
                    })
                    if(origin_item){
                        // 20221007 modify by Alan for #112097	 : 依照ori_FinalQTY判斷要回寫FinalQTY還是qty
                        $scope.warehouseInfo.plot_info_detail[origin_item_key].qty = data.qty;
                        $scope.warehouseInfo.plot_info_detail[origin_item_key].FinalQTY = data.FinalQTY;
                        $scope.warehouseInfo.plot_info_detail[origin_item_key].storage_qty = data.storage_qty;
                        $scope.selectedList.splice(index, 1);
                    }else{
                        // $scope.warehouseInfo.plot_info_detail.push(data);
                        $scope.warehouseInfo.plot_info_detail.splice(data.warehouse_index,0,data)
                        $scope.selectedList.splice(index, 1);
                    }
                }
                //20210419 Modify by德義家興for#91013: [标准][DEV][行业议题]机加工-CNC良品工单汇总显示
                calculate_sum();
            };

            function check_select_list(click_data,key){//如果已選清單有該則入庫項目，清掉原項目並新增該項目
                if(typeof(key) == 'number' && key!==-1){
                    $scope.selectedList.splice(key,1);
                }
                //20220610 add by 翰鴻 for M#108133
                click_data.item_no_OG = click_data.item_no;
                $scope.selectedList.unshift(angular.copy(click_data)); // 20200914 modify by WeiTing for M#78029 - 修改下方聯產品時不可同步異動到上方未選擇的資料。
                //20210428 Modify by德義家興for#91013: [标准][DEV][行业议题]机加工-CNC良品工单汇总显示
                calculate_sum();
            }

            function check_select_list_repeat(data){ //檢查重複
                let repeatStorage = -1;
                $scope.selectedList.forEach(function(item,key){
                    if(item.wo_no === data.wo_no && item.plot_no === data.plot_no && item.item_name === data.item_name){
                         //有重複輸入
                         repeatStorage = key; 
                    }    
                });
                return repeatStorage;
            }

            //20210419 Modify by德義家興for#91013: [标准][DEV][行业议题]机加工-CNC良品工单汇总显示
            //計算數量總和
            function calculate_sum(){ //時機是按下 查詢按鈕,選擇按鈕,+號按鈕,-號按鈕
                var sum = 0;
                if ($scope.warehouseInfo.plot_info_detail.length > 0) {
                    $scope.warehouseInfo.plot_info_detail.forEach(function(item){                    
                        sum += parseInt(item.qty,10);
                    });
                    $scope.unselected_sum = sum;
                    sum = 0;    
                }else {
                    $scope.unselected_sum = 0;
                }
                if ($scope.selectedList.length > 0) {
                    $scope.selectedList.forEach(function(item){                    
                        sum += parseInt(item.storage_qty,10);
                    });
                    $scope.selected_sum = sum;
                    sum = 0;
                }else {
                    $scope.selected_sum = 0;
                }
            };

            $scope.itemCheck = function (index, data) {
                var msg = '';
                //20170328 modify by megabytes for 良品與不良品判斷依據不同，並判斷是否已重複選取
                //20170329 modify by megabytes for 良品判斷條件多增加數量。
                // if($scope.type == 0){
                //     for(var i = 0 ; i < $scope.selectedList.length ; i++){
                //         if($scope.selectedList[i].plot_no == data.plot_no && $scope.selectedList[i].qty == data.qty){
                //             msg = $filter('translate')('B0401.msg.repeat');
                //             break;
                //         }
                //     }
                // }else 
                if ($scope.type == 1){
                    for(var i = 0 ; i < $scope.selectedList.length ; i++){
                        //20180425 modify by Dustdusk for 相同生產批不同不良原因要能選擇
                        if($scope.selectedList[i].lot_serial == data.lot_serial && $scope.selectedList[i].error_no == data.error_no){
                            msg = $filter('translate')('B0401.msg.repeat');
                            break;
                        }
                    }
                }

                //20220823 add by 翰鴻 for M#106435
                if (data.OPGROUPNO == 'N/A')
                    msg = $filter('translate')('B0401.msg.no_opgroupno');

                if(msg != ''){
                    $scope.$root.showAlert(msg);
                } else {
                    //20220629 add by 翰鴻 for M#106435
                    //http://10.40.140.178:81/mantis/view.php?id=106435#c483146
                    setBody(data);
                    
                };
            };

             //20200421 modify by Oliver for M#70010 標準功能開發_ 分量入庫
            // 20221007 modify by Alan for #112097	 : 修正FQC邏輯
            $scope.openNumChangebox=function(data,repeatStorage){
                $mddProvider.UseForm('B0401_ChangeNum', () =>{
                    $mdDialog.dialog(
                        'module/moduleB/program/B04/B0401/B0401_ChangeNum.tmp.html',
                        function(dialog){
                            return {
                                _fn: {
                                    Execute: {
                                        click: () => {
                                            dialog.confirm();
                                        }
                                    }
                                },
                                storage_qty: (data.IsNeedFQC
                                    ? (+data.ori_FinalQTY) - (+data.storage_qty)
                                    : ((+data.FinalQTY) ? (+data.ori_FinalQTY) - (+data.storage_qty) : (+data.ori_qty) + (+data.ori_FinalQTY) - (+data.storage_qty))) || 0,
                                already_storage_qty: data.storage_qty || 0,
                                storage_plot: data.plot_no,
                                repeatStorage,//repeatStorage=-1代表這筆入庫資料在selectList中不存在。
                                qty: data.FinalQTY || data.qty,
                                back: function () {
                                    dialog.hide();
                                },
                                confirm:function(){
                                    if(dialog.repeatStorage == -1) { //沒有重複輸入
                                        if(dialog.qty - dialog.storage_qty >= 0) {
                                            if((+data.FinalQTY) > 0) {
                                                data.FinalQTY = (+dialog.qty) - (+dialog.storage_qty);
                                            } else {
                                                data.qty = (+dialog.qty) - (+dialog.storage_qty);
                                            }
                                            data.storage_qty=dialog.storage_qty;
                                            data.checked = !data.checked;
                                            data.storage_plot = dialog.storage_plot;
                                            var _index = $scope.warehouseInfo.plot_info_detail.indexOf(data);
                                            data.warehouse_index=_index;
                                            check_select_list(data,dialog.repeatStorage);
                                            //20200422分量入庫 modify by Oliver 如果入庫的數量減去總量等於零，則移除該項目在陣列中的位置，如果否，更新數字上去
                                            // 2022-10-13 #0112097 FQC 不移除此列，僅調整數量 start
                                            // if(Number(dialog.qty) - Number(dialog.storage_qty) === 0){
                                            //     $scope.warehouseInfo.plot_info_detail.splice(_index, 1); 
                                            // }
                                            // 2022-10-13 #0112097 FQC 不移除此列，僅調整數量 end
                                            dialog.hide();
                                        } else {
                                            showAlert($filter('translate')('B0401_StoragePlot.msg.storage_qty_exceed_qty'));
                                        }
                                    } else {
                                        if(dialog.qty - dialog.storage_qty >= 0){
                                            if((+data.FinalQTY) > 0) {
                                                data.FinalQTY = (+dialog.qty) - (+dialog.storage_qty);
                                            } else {
                                                data.qty = (+dialog.qty) - (+dialog.storage_qty);
                                            }
                                            data.storage_qty = (+data.storage_qty) + (+dialog.storage_qty);
                                            data.storage_plot = dialog.storage_plot;
                                            var _index = $scope.warehouseInfo.plot_info_detail.indexOf(data);
                                            data.warehouse_index=_index;
                                            check_select_list(data,dialog.repeatStorage);
                                            // 2022-10-13 #0112097 FQC 不移除此列，僅調整數量 start
                                            // if((+dialog.qty) === ((+dialog.already_storage_qty) + (+dialog.storage_qty))){
                                            //     $scope.warehouseInfo.plot_info_detail.splice(_index, 1); 
                                            // }
                                            // 2022-10-13 #0112097 FQC 不移除此列，僅調整數量 end
                                            dialog.hide();
                                        } else {
                                            showAlert($filter('translate')('B0401_StoragePlot.msg.storage_qty_exceed_qty'));
                                        }
                                    };
                                }
                            }
                        }
                    )
                })
            },

            // 20191213 modify by WeiTing for M#63727 - 追溯模組 - 車間要設定批號控管才能開窗。
            $scope.openStoragePlot = function (data,repeatStorage) { //row 跟 是否重複
                $mddProvider.UseForm('B0401_StoragePlot', () =>{
                    $mdDialog.dialog(
                        'module/moduleB/program/B04/B0401/B0401_StoragePlot.tmp.html',
                        function (dialog) {
                            // 2023-06-17
                             // 20231016 modify by shiwl for  0147892: 【东声】良品入库数量取值逻辑错误
                             dialog.storage_qty= data.IsNeedFQC ? data.FinalQTY : data.FinalQTY > 0 ? data.FinalQTY : data.qty;
                            return {
                                //dialog._event['num'].isShown != 'N'
                                _fn: {
                                    clear_plot: {
                                        click: () => {
                                            dialog.clearPlot();
                                        }
                                    },
                                    confirm: {
                                        click: () => {
                                            dialog.confirm();
                                        }
                                    }                                    
                                },
                                _event: {
                                    num: {
                                        isShown: $scope.changeNumOrNot == 1 ? 'Y' : 'N'
                                    },
                                    total_num: {
                                        isShown: $scope.changeNumOrNot == 1 ? 'Y' : 'N'
                                    },
                                    plot_no: {
                                        isShown: $scope.changeNumOrNot == 1 ? 'Y' : 'N'
                                    },
                                },
                                storage_qty: dialog.storage_qty,
                                //20210831 modify by John for M#97202: 配合後端調整，一律以mo_stockinlotno取代入庫批次號
                                storage_plot: data.mo_stockinlotno,
                                changeNumOrNot:$scope.changeNumOrNot,
                                repeatStorage,
                                qty:data.IsNeedFQC ? data.FinalQTY :  data.FinalQTY>0 ? data.FinalQTY :data.qty,
                                //20211008 modify by Jason for M#0100224: [HOTFIX_3.2.2.1121發版測試]入庫選數量修改時,修改入庫批次號,理論上生產批號不該跟著變
                                plot_no:data.plot_no,
                                back: function () {
                                    dialog.hide();
                                },
                                clearPlot: function () {
                                    dialog.storage_plot = '';
                                },
                                //20200421 modify by Oliver for M#70010 標準功能開發_ 分量入庫
                                confirm: function () {
                                    if( dialog.storage_qty > dialog.qty) {
                                        showAlert($filter('translate')('B0401_StoragePlot.msg.storage_qty_exceed_qty'));
                                        return;
                                       } else {
                                        var _index = $scope.warehouseInfo.plot_info_detail.indexOf(data);
                                        if(dialog.repeatStorage == -1){//沒有重複輸入
                        
                                            // data.storage_qty=dialog.storage_qty;//更新入庫數量
                                            if (data.IsNeedFQC) {
                                                // 2023-06-17
                                                data.storage_qty += (+dialog.storage_qty);
                                                data.FinalQTY -= (+dialog.storage_qty);
                                            } else {
                                                if(data.ori_FinalQTY > 0) {
                                                    // 當不需要 FQC 時，最終數量=0時，需加上生產數量
                                                    if (data.FinalQTY == 0) {
                                                        data.storage_qty = (+data.ori_FinalQTY) + (+data.qty);
                                                        data.qty = 0;
                                                    } else {
                                                        //20230816 modify by shiwl for M0143456: 东声电子：良品入库，修改入库数量，数量变负数，无法入库, 转出数量为总量问题修改,修改为转出数量
                                                        data.storage_qty = (+dialog.storage_qty);
                                                        data.FinalQTY -= (+dialog.storage_qty);
                                                    }
                                                } else {
                                                    if($scope.open_off_two) {
                                                        data.storage_qty = (+dialog.storage_qty);
                                                        data.qty -= (+dialog.storage_qty);
                                                    } else {
                                                         data.storage_qty = data.qty;
                                                         data.qty = 0;
                                                    }
                                                }
                                            }
                                                                              
                                            //20210428 Modify by德義家興for#91013: [标准][DEV][行业议题]机加工-CNC良品工单汇总显示
                                            // if(dialog.storage_plot != ''){
                                            //     data.storage_plot = dialog.storage_plot;
                                                if (dialog.storage_plot != '') {
                                                    data.storage_plot = dialog.storage_plot;
                                                } else{
                                                    data.storage_plot = data.plot_no;
                                                }
                                                data.checked = !data.checked;
                                                if(Number(dialog.qty) - Number(dialog.storage_qty) >= 0){//如果入庫數量等於
                                                    // 2023-06-07
                                                    data.warehouse_index=_index;
                                                    check_select_list(data,dialog.repeatStorage);
                                                    // $scope.selectedList.push(data);
                                                    if(Number(dialog.qty) -Number(dialog.storage_qty) == 0){
                                                        if(data.IsNeedFQC == false){
                                                            // $scope.warehouseInfo.plot_info_detail.splice(_index, 1); 
                                                        }
                                                    }
                                                    dialog.hide();  
                                                }
                                           
                                        } else {
                                            /*如有bug優先檢查此處，當selectlist有值時的檢查*/ 
                                            if((+dialog.qty) - (+dialog.storage_qty) >= 0){
                                                // data.qty=(+dialog.qty) - (+dialog.storage_qty);
                                                // data.storage_qty = (+data.storage_qty) + (+dialog.storage_qty);
                                                if (data.IsNeedFQC) {
                                                    // 2023-06-17
                                                    data.storage_qty += (+dialog.storage_qty);
                                                    data.FinalQTY -= (+dialog.storage_qty);
                                                } else {
                                                    if(data.ori_FinalQTY > 0) {
                                                        // 當不需要 FQC 時，最終數量=0時，需加上生產數量
                                                        if (data.FinalQTY == 0) {
                                                            data.storage_qty = (+data.ori_FinalQTY) + (+data.qty);
                                                            data.qty = 0;
                                                        } else {
                                                            data.storage_qty = data.ori_FinalQTY;
                                                            data.FinalQTY = 0;
                                                        }
                                                    } else {
                                                        data.storage_qty = data.qty;
                                                        data.qty = 0;
                                                    }
                                                }
                                            
                                                data.storage_plot = data.plot_no;
                                                check_select_list(data,dialog.repeatStorage);
                                                var _index = $scope.warehouseInfo.plot_info_detail.indexOf(data);
                                                // 2022-10-13 #0112097 FQC 不移除此列，僅調整數量 start
                                                // if(data.qty == 0){
                                                //     $scope.warehouseInfo.plot_info_detail.splice(_index, 1); 
                                                // }
                                                // 2022-10-13 #0112097 FQC 不移除此列，僅調整數量 end
                                                dialog.hide();
                                            }
                                        }
                                      }
                                   
                                } 
                            }
                        }
                    );
                })
            };

            $scope.openStorage = function (sameInventoryAndStorage) {
                $scope.sameInventoryAndStorage = sameInventoryAndStorage;
                $mddProvider.UseForm('B0401_SearchPlot', () =>{
                    $mdDialog.dialog(
                        'module/moduleB/program/B04/B0401/B0401_SearchPlot.tmp.html',
                        storageController
                    );
                })
            };

            function storageController(dialog) {
                var controller = {
                    _fn: {
                        'Execute': {
                            click: () => {
                                dialog.confirm();
                            }
                        }
                    },
                    type:$scope.type,
                    warehouseInfo: $scope.warehouseInfo,
                    //成品庫
                    init: function() {
                        // 20200917 modify by WeiTing for M#72157 - 如果選取的資料的倉庫和儲位都相同時，判斷是否跟下拉式選單的資料符合，符合就預設為此倉庫和儲位。
                        var conditionvalue = 1;
                        // 良品 = 1 , 不良品 =3
                        if($scope.type == 1){
                            conditionvalue = 3;
                        } else {
                            conditionvalue = 1;
                        }
                        pageNumberInfoGet({
                            // 倉庫
                            page_mode : '13',
                            query_condition_info : [
                                { column_name:'InventoryType', query_mode:'0', value:conditionvalue }
                            ]
                        }, function (response) {
                            if(response && response.length > 0){
                                for(var i = 0; i < response.length; i++){
                                    // 判斷倉庫是否跟下拉式選單的資料符合
                                    if(response[i].page_no === $scope.sameInventoryAndStorage.inventoryNo){
                                        $scope.warehouseInfo.product_warehouse_name = response[i].page_name;
                                        $scope.warehouseInfo.product_warehouse = response[i].page_no;

                                        $scope.warehouseInfo.storage = '';
                                        $scope.warehouseInfo.storage_display = '';
                                        break;
                                    }
                                }
                            }    
                            pageNumberInfoGet({
                                // 儲位
                                page_mode : 14, 
                                query_condition_info : [
                                    {column_name:'InventoryNo', query_mode:'0', value:$scope.warehouseInfo.product_warehouse}
                                ]
                            }, function (response) {
                                if(response && response.length > 0){
                                    for(var i = 0; i < response.length; i++){
                                        // 判斷儲位是否跟下拉式選單的資料符合
                                        if(response[i].page_no === $scope.sameInventoryAndStorage.storageSpacesNo){
                                            $scope.warehouseInfo.storage = response[i].page_no;
                                            $scope.warehouseInfo.storage_display = response[i].page_name;
                                            break;
                                        }
                                    }
                                }
                            });          
                        });   
                    },
                    loadProductWarehouse: function () {
                        // 良品 = 1 , 不良品 =3
                        var conditionvalue = 1;
                        if($scope.type == 1){
                            conditionvalue = 3;
                        } else {
                            conditionvalue = 1;
                        }
                        pageNumberInfoGet({
                            page_mode : '13',
                            query_condition_info : [
                                { column_name:'InventoryType', query_mode:'0', value:conditionvalue }
                            ]
                        }, function (response) {
                            $scope.$root.showSelect({
                                title: $filter('translate')('B0401.otherTitle.column1'),
                                label: function(item){
                                    return item.page_no + ' ('+ item.page_name +')';
                                },
                                code: 'page_no',
                                selectCode: $scope.warehouseInfo.product_warehouse,
                                list: response,
                                confirm: function (item, dialog) {
                                    dialog.hide();
                                    $scope.warehouseInfo.product_warehouse_name = item.page_name;
                                    $scope.warehouseInfo.product_warehouse = item.page_no;

                                    $scope.warehouseInfo.storage = '';
                                    $scope.warehouseInfo.storage_display = '';
                                }
                            });
                        });
                    },
                    //儲位
                    loadStorage: function () {
                        if($scope.warehouseInfo.product_warehouse != ''){
                            pageNumberInfoGet({page_mode: 14, query_condition_info :[
                                {column_name:'InventoryNo', query_mode:'0', value:$scope.warehouseInfo.product_warehouse}
                            ]}, function (response) {
                                $scope.$root.showSelect({
                                    title: $filter('translate')('B0401.otherTitle.column1'),
                                    label: function(item){
                                        return item.page_no + ' ('+ item.page_name +')';
                                    },
                                    code: 'page_no',
                                    selectCode: $scope.warehouseInfo.storage,
                                    list: response,
                                    confirm: function (item, dialog) {
                                        dialog.hide();
                                        $scope.warehouseInfo.storage = item.page_no;
                                        $scope.warehouseInfo.storage_display = item.page_name;
                                    }
                                });
                            });
                        } else {
                            $scope.$root.showAlert($filter('translate')('B0401.msg.product_warehouse_empty'));
                        }

                    },
                    loadERP: function () {
                        $rootScope.showQueryList({
                            pageRecord:50,
                            header : [
                                {label:$filter('translate')('B0216.queryList.column3_1'), code:'page_no'},
                                {label:$filter('translate')('B0216.queryList.column3_2'), code:'page_name'}
                            ],
                            query: function(conditions, feedback){
                                $MMWService.sendToServer({
                                    uri: 'ServicesSTD.Module_SYS.erp_document_type_get',
                                        // $mddProvider.Getfunc('B0401_SearchPlot','erp_document_type_get'),
                                    content: { doc_type:$scope.do_flag == 0?'1':'6' },
                                    success: function (data) {
                                        feedback(data);
                                    }
                                });
                            },
                            selectCode:$scope.warehouseInfo.erp_doc_type,
                            confirm : function(selectItem, dialog){
                                $scope.warehouseInfo.erp_doc_type = selectItem.page_no;
                                dialog.hide();
                            }
                        });
                    },
                    back: function () {
                        $scope.warehouseInfo.product_warehouse_name = '';
                        $scope.warehouseInfo.product_warehouse = '';
                        $scope.warehouseInfo.storage = '';
                        $scope.warehouseInfo.storage_display = '';
                        $scope.warehouseInfo.erp_doc_type = '';
                        dialog.hide();
                    },
                    confirm: function () {
                        if($scope.type==0){
                            if($scope.warehouseInfo.product_warehouse.length == 0) {
                                $rootScope.showAlert($filter('translate')('B0401.showAlert.column3'));
                            } else {
                                dialog.hide();
                                warehousePlotProcess();
                            }
                        } else if($scope.type == 1){
                            dialog.hide();
                            warehousePlotProcess();
                        }
                    }
                }
                return controller;
            }

            //取得單號
            // 1 工單編號 6產品編號 13成品庫 14儲位
            function pageNumberInfoGet(content, feedback) {
                $MMWService.pageNumberInfoGet(
                    content
                    , function (itemList) {
                        feedback(itemList);
                });
            }


            //取得待入庫資料
            //type 0:良品  1:不良品
            function warehousePlotInfoGet(content, feedback) {
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.warehouse_plot_info_get',
                        // $mddProvider.Getfunc('B0401', 'warehouse_plot_info_get'),
                    content: content,
                    success: function (data) {
                        //20220610 add by 翰鴻 for M#108133
                        if (data.ERP_Name) $scope.ERP_Name = data.ERP_Name;
                        feedback(data.warehouse_plot_info_get);
                    }
                });
            }

            //送出確定的待入庫資料
            //type 0:良品 1:不良品
            function warehousePlotProcess() {
                var msg = '';
                var content = {
                    type: $scope.type,
                    product_warehouse: $scope.warehouseInfo.product_warehouse,
                    storage: $scope.warehouseInfo.storage,
                    erp_doc_type: $scope.warehouseInfo.erp_doc_type,
                    do_flag: $scope.do_flag,
                    do_print: $scope.do_print,
                    warehouse_datetime:new Date(),
                    plot_info_detail: []
                };
                if($scope.warehouseInfo.select_type == 2){
                    content.type = 2;
                //20170612 modify by Dustdusk for 新增warehouseInfo.select_type = 4 (作廢)
                } else if($scope.warehouseInfo.select_type == 4){
                    content.type = 3;
                }
                for(var index in $scope.selectedList){
                    var item = $scope.selectedList[index];
                    // 20210422 modifyBy 14581 for M#89226 : 不良品判定增加傳遞線邊倉參數
                    var plot_info_detail = {
                        plot_no: item.plot_no,
                        lot_code: item.storage_plot,
                        op_no: item.op_no,
                        lot_serial: item.lot_serial ,
                        // 生產數量
                        qty: item.ori_qty - item.qty,
                        // 入庫數量
                        plot_qty: item.storage_qty,
                        // 20221007 modify by Alan for #112097：　新增finalQty供後端判斷
                        final_qty: item.ori_FinalQTY - item.FinalQTY,
                        error_no: item.error_no,
                        do_flag:item.DOFlag,
                        log_group_serial: item.log_group_serial,
                        InventoryNo: item.inventoryno,
                        mes_inventoryNo: item.mes_inventoryNo,
                        // 20210422 modifyBy liuyang for M#98099 : 入庫資料寫入錯誤
                        product_no: item.item_no,
                        product_ver:item.item_ver
                    };
                     // 20210629 add By 14169 for M#94866: 未开启lot_code传空
                     if (item.StockLotNo == '0') {
                        plot_info_detail.lot_code = ''; 
                    }
                    /*20200422 modify by Oliver 分量入庫 plot_qty為扣除轉出後剩餘總量不必再於後端扣除一次*/
                    if($scope.warehouseInfo.select_type == 4){
                        if(item.cancel_qty == undefined || item.cancel_qty == 0){
                            msg = $filter('translate')('B0401.msg.cancel_qty_empty');
                            break;
                        } else if(item.cancel_qty == undefined || item.cancel_qty == 0){
                            msg = $filter('translate')('B0401.msg.cancel_qty_gt');
                            break;
                        }
                        plot_info_detail.cancel_qty = item.cancel_qty;
                    }
                    //20220907 add by 翰鴻 for M#117105
                    else if ($scope.warehouseInfo.select_type == 3) {
                        if (item.storage_qty != item.serialNo_qty && (item.DEFAULTVALUE != null && (item.DEFAULTVALUE.indexOf('only scan') != -1 || item.DEFAULTVALUE.indexOf('select') != -1))) {
                            msg = $filter('translate')('B0401.msg.qty_not_equal', { qty1: item.storage_qty, qty2: item.serialNo_qty });
                            break;
                        }
                    }
                    if($scope.type == '0'){
                        if(item.joint_trigger == undefined){
                            plot_info_detail.joint_trigger = 'N';
                        } else {
                            plot_info_detail.joint_item_no = item.joint_item_no;
                            plot_info_detail.joint_item_unit_no = item.joint_item_unit_no;
                            plot_info_detail.joint_trigger = 'Y';
                        }
                    }
                    content.plot_info_detail.push(plot_info_detail);
                    //content.op_no = item.op_no;
                }
                if(msg == ''){
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_WIP.warehouse_plot_process',
                            // $mddProvider.Getfunc('B0401_SearchPlot','warehouse_plot_process'),
                        content: content,
                        success: function (data, response) {
                            //20180514 modify by Dustdusk for M#46940:入庫完成的訊息由後台提供 請抓 response.Message
                            var msg = $filter('translate')('B0401.msg.process_success');
                            if(response.Message != undefined && response.Message!=''){
                                msg = response.Message;
                            }
                            //20170330 modify by megabytes for 確認存取完後清空
                            $scope.warehouseInfo.item_name = '';
                            $scope.warehouseInfo.plot_no = '';
                            $scope.selectedList = [];

                            // 20200902 modify by WeiTing for M#74338: 增加系統參數(WarehouseShowERPNo)來判斷入庫單號是否顯示確認跳窗，讓使用者記錄完後，自行關閉。
                            if(config.cache.sys_parameter.WarehouseShowERPNo === 'Y'){
                                $scope.$root.showCheck(msg, function(confirm_dialog){
                                    confirm_dialog.hide();
                                });
                            } else {
                                $scope.$root.showToast(msg, 10);
                            }

                            $scope.search('research');
                        }
                    });
                } else {
                    $scope.$root.showAlert(msg);
                }
            }

            function setBody(data) {
                //20220901 add by 翰鴻 for M#117105
                data.serialNo_qty = 0;
				
				// 2023-06-07
                {
                    // 20221007 modify by Alan for #112097	 :  
                    // 当产品需要FQC时，tblinvwipinventory_semi.FinalQty >0 
                    // 最终数量大於0，则加入「最终数量」至「待出库清单中」，
                    // 则跳出错误信息
                    // 当产品不需要FQC时，tblinvwipinventory_semi.FinalQty >0 
                    // 最终数量大於0，则加入「最终数量」至「待出库清单中」；
                    // tblinvwipinventory_semi.FinalQty =0 最终数量等於0时，则加入「生产数量 Qty」至「待出库清单中」，
                    // 生产数量 Qty及 最终数量 FinalQty 都为0 时，则跳出错误信息
                    if(data.IsNeedFQC) {
                        if(+data.FinalQTY <= 0) {
                            $rootScope.showAlert($filter('translate')('B0401.msg.plot_qty_is_zero', {plot_no: data.plot_no}));
                            return;
                        } 
                    } else {
                        if(+data.FinalQTY <= 0 && +data.qty <= 0) {
                            $rootScope.showAlert($filter('translate')('B0401.msg.plot_qty_is_zero', {plot_no: data.plot_no}));
                            return;
                        }
                    }
                }
				
                // 2020 分量入庫 modify by Oliver for M#70010 做不同類型入庫時的卡控
                if ($scope.selectedList.length > 0) {
                    //20220525 add by 翰鴻 for M#106435
                    var diffList = $.grep($scope.selectedList, function (n, i) {
                        return n.OPGROUPNO != data.OPGROUPNO
                    });

                    if (diffList.length > 0) {
                        var opgroupno2 = diffList[0].OPGROUPNO;
                        showAlert($filter('translate')('B0401.msg.opgroupno_different', { opgroupno1: data.OPGROUPNO, opgroupno2: opgroupno2 }));
                        return false;
                    }

                    //20220610 add by 翰鴻 for M#108133
                    if ($scope.do_flag == 1 && ($scope.ERP_Name == 'T100' || $scope.ERP_Name == 'TIPTOP')) {
                        var diff_wo_no_List = $.grep($scope.selectedList, function (n, i) {
                            return n.wo_no != data.wo_no
                        });
                        if (diff_wo_no_List.length > 0) {
                            //T系列當站下線入庫單需相同工單號，請重新選取
                            showAlert($filter('translate')('B0401.msg.wo_no_different'));
                            return false;
                        }
                    }
                    /*檢查是否重覆改變數量*/
                    let repeatStorage = check_select_list_repeat(data);//檢查selectList內有無同一筆資料
                    if ($scope.selectedList[0].DOflag != data.DOflag) {
                        showAlert($filter('translate')('B0401.msg.type_not_the_same'));
                    } else {
                        // 20191213 modify by WeiTing for M#63727 - 追溯模組 - 批號控管 - StockLotNo - 0:不啟用、1:啟用 (P.S. 只有良品才能開窗)
                        if ($scope.type == 0 && data.StockLotNo == '1') {
                            $scope.openStoragePlot(data, repeatStorage);
                        } else {
							
                            // 2023-06-07
                            { 
                            /* // 20221007 modify by Alan for #112097	 :  
                            // 当产品需要FQC时，tblinvwipinventory_semi.FinalQty >0 
                            // 最终数量大於0，则加入「最终数量」至「待出库清单中」，
                            // 则跳出错误信息
                            // 当产品不需要FQC时，tblinvwipinventory_semi.FinalQty >0 
                            // 最终数量大於0，则加入「最终数量」至「待出库清单中」；
                            // tblinvwipinventory_semi.FinalQty =0 最终数量等於0时，则加入「生产数量 Qty」至「待出库清单中」，
                            // 生产数量 Qty及 最终数量 FinalQty 都为0 时，则跳出错误信息
                            if(data.IsNeedFQC) {
                                if(+data.FinalQTY <= 0) {
                                    $rootScope.showAlert($filter('translate')('B0401.msg.plot_qty_is_zero', {plot_no: data.plot_no}));
                                    return;
                                } 
                            } else {
                                if(+data.FinalQTY <= 0 && +data.qty <= 0) {
                                    $rootScope.showAlert($filter('translate')('B0401.msg.plot_qty_is_zero', {plot_no: data.plot_no}));
                                    return;
                                }
                            }
                            */ }
							
                            data.storage_plot = data.plot_no
                            if ($scope.changeNumOrNot == 1) {
                                $scope.openNumChangebox(data, repeatStorage);
                            } else {
                                // 2022-10-13 #0112097 FQC 不移除此列，僅調整數量 start
                                if (data.IsNeedFQC) {
                                    data.storage_qty = data.ori_FinalQTY;
                                    data.FinalQTY = 0;
                                } else {
                                    if(data.ori_FinalQTY > 0) {
                                        // 當不需要 FQC 時，最終數量=0時，需加上生產數量
                                        if (data.FinalQTY == 0) {
                                            data.storage_qty = (+data.ori_FinalQTY) + (+data.qty);
                                            data.qty = 0;
                                        } else {
                                            data.storage_qty = data.ori_FinalQTY;
                                            data.FinalQTY = 0;
                                        }
                                    } else {
                                        data.storage_qty = data.qty;
                                        data.qty = 0;
                                    }
                                }
                                data.checked = !data.checked;
                                // var _index = $scope.warehouseInfo.plot_info_detail.indexOf(data);
                                // $scope.warehouseInfo.plot_info_detail.splice(_index, 1);
                                // 2022-10-13 #0112097 FQC 不移除此列，僅調整數量 end
                                //20200806 add by Oliver 比對已選擇欄位有無此資料
                                check_select_list(data, repeatStorage);
                            }
                        };
                    }
                } else {
                    // 20191213 modify by WeiTing for M#63727 - 追溯模組 - 批號控管 - StockLotNo - 0:不啟用、1:啟用 (P.S. 只有良品才能開窗)
                    if ($scope.type == 0 && data.StockLotNo == '1') {
                        $scope.openStoragePlot(data, -1);
                    } else {
						
                        // 2023-06-07
                        { 
                        /* // 20221007 modify by Alan for #112097	 :  
                        // 当产品需要FQC时，tblinvwipinventory_semi.FinalQty >0 
                        // 最终数量大於0，则加入「最终数量」至「待出库清单中」，
                        // 则跳出错误信息
                        // 当产品不需要FQC时，tblinvwipinventory_semi.FinalQty >0 
                        // 最终数量大於0，则加入「最终数量」至「待出库清单中」；
                        // tblinvwipinventory_semi.FinalQty =0 最终数量等於0时，则加入「生产数量 Qty」至「待出库清单中」，
                        // 生产数量 Qty及 最终数量 FinalQty 都为0 时，则跳出错误信息
                        if(data.IsNeedFQC) {
                            if(+data.FinalQTY <= 0) {
                                $rootScope.showAlert($filter('translate')('B0401.msg.plot_qty_is_zero', {plot_no: data.plot_no}));
                                return;
                            } 
                        } else {
                            if(+data.FinalQTY <= 0 && +data.qty <= 0) {
                                $rootScope.showAlert($filter('translate')('B0401.msg.plot_qty_is_zero', {plot_no: data.plot_no}));
                                return;
                            } 
                        }
                        */ }
						
                        data.storage_plot = data.plot_no
                        if ($scope.changeNumOrNot == 1) {
                            $scope.openNumChangebox(data, -1);
                        } else {
                            // 2022-10-13 #0112097 FQC 不移除此列，僅調整數量 start
                            if (data.IsNeedFQC) {
                                data.storage_qty = data.ori_FinalQTY;
                                data.FinalQTY = 0;
                            } else {
                                if(data.ori_FinalQTY > 0) {
                                    // 當不需要 FQC 時，最終數量=0時，需加上生產數量
                                    if (data.FinalQTY == 0) {
                                        data.storage_qty = (+data.ori_FinalQTY) + (+data.qty);
                                        data.qty = 0;
                                    } else {
                                        data.storage_qty = data.ori_FinalQTY;
                                        data.FinalQTY = 0;
                                    }
                                } else {
                                    data.storage_qty = data.qty;
                                    data.qty = 0;
                                }
                            }
                            data.checked = !data.checked;
                            // var _index = $scope.warehouseInfo.plot_info_detail.indexOf(data);
                            // 非裝程完工，一致性不移除此列
                            // $scope.warehouseInfo.plot_info_detail.splice(_index, 1);
                            // 2022-10-13 #0112097 FQC 不移除此列，僅調整數量 end
                            check_select_list(data, -1);
                        }
                    };
                }
            }

            $scope.changeSelectType = function(type){
                if($scope.warehouseInfo.select_type == 4 && type != 4){
                    $scope.selectedList.forEach(function(selectItem) {
                        selectItem.cancel_qty = undefined;
                    });
                }
                $scope.warehouseInfo.select_type = type;
            };

            $scope.input_cancel_qty = function (event, item) {
                var target = event.currentTarget;
                angular.element(target).addClass('is-focus');
                $calculater.open(function (num, dialog) {
                        angular.element(target).removeClass('is-focus');
                        if(num == 0){
                            $scope.$root.showAlert($filter('translate')('B0401.msg.cancel_qty_empty'));
                        } else if ((+num) > (+item.qty)){
                            $scope.$root.showAlert($filter('translate')('B0401.msg.cancel_qty_gt'));
                        } else {
                            item.cancel_qty = num;
                            dialog.hide();
                        }
                    },
                    function (dialog) {
                        angular.element(target).removeClass('is-focus');
                        dialog.hide();
                    },
                    {
                        defaultNum: item.cancel_qty ,
                        decimal: false
                    });
            };

            $scope.product_change = function(event, item){
                $mdDialog.serviceDialog('B0223Service',{
                    parent : 'B0401',
                    plotItem : item,
                    do_flag:$scope.do_flag,
                    close : function(newItem){
                        item.item_no = item.joint_item_no; //  20240221 modify by shiwl for #0157806: [sMES] 聯產品入庫時已選取好的品號再次點進選單後，點選關閉視窗，品號會跳回原生產批品號 [應用奈米]
                        item.item_name = newItem.item_name;
                        item.item_unit_no = newItem.item_unit_no;
                        item.item_ver = newItem.item_ver;
                    },
                    feedback : function(newItem){
                        item.old_item_no = item.item_no;
                        item.old_item_name = item.item_name;
                        item.old_item_unit_no = item.item_unit_no;
                        item.old_item_ver = item.item_ver;

                        item.joint_item_no = item.item_no = newItem.joint_item_no;
                        item.item_name = newItem.joint_item_name;
                        item.joint_item_unit_no = item.item_unit_no = newItem.joint_item_unit_no;
                        item.item_ver = newItem.joint_item_ver;
                        item.joint_trigger = 'Y';
                    }
                });
            };
            //  20240321 modify by shiwl for #0160146: 丹尼入库界面报工还原 
            $scope.callB0225 = function(item){     
                // 先根据制程完成状态，再根据权限判断          
                if(!config.cache.permissions || config.cache.permissions.indexOf('B022505')!=-1){
                   if(!$scope.do_flag) { // 制程完成
                       $mdDialog.serviceDialog('B0225Service',{
                        parent:'B0401',
                        plotItem : item,
                        callback : function(){
                            $scope.search();
                        }
                     });
                   } else {
                     $scope.openRollBackDialog(item);
                   }
                } else { 
                    $scope.$root.showAlert($filter('translate')('B0401.msg.no_permissions_have been_set_for_this_function'));
                }
             
            };

            // 20220422 modify by Alan for #102658	 :  [sMES 研發組(標準產品)] : 入庫單拋轉失敗可重新拋轉機制
            // 背景刷新入庫異常資料，自訂入庫異常資料開窗
            function getLight(feedback, isShowLoading)  {
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.warehouse_fail_eaiqueue_info_get',
                        // $mddProvider.Getfunc('B0401','warehouse_fail_eaiqueue_info_get'),
                    content : {
                        StockIn_Type: 0
                    },
                    success : function(data){
                        $scope.isStorageExceptionDisabled = (data.light != 'red');
                        try{
                            feedback(feedback, isShowLoading);
                        }catch(e){console.log(e);}
                    },
                }, isShowLoading);
            }

            $scope.openStorageExceptionDialog = function(event){
                var btnIsEnable = !event.currentTarget.getAttribute('disabled');
                if(btnIsEnable) {
                    $mddProvider.UseForm('B0401_StorageException', () =>{
                        $mdDialog.dialog(
                            'module/moduleB/program/B04/B0401/B0401_StorageException.tmp.html',
                            storageExceptionDialogController
                        )
                    })
                }
            }

            function storageExceptionDialogController(dialog) {
                dialog.currentItemID = '';
                dialog.exceptionMsg = '';
                dialog.myFilter = {};
                dialog.DetailFilter = {};
                dialog.infoBasis = [];
                dialog.infoDetail = [];

                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.warehouse_fail_eaiqueue_info_get',
                        // $mddProvider.Getfunc('B0401_StorageException', 'warehouse_fail_eaiqueue_info_get'),
                    content: {
                        Info_Flag: "Basis",
                        StockIn_Type: 0
                    },
                    success: function (data) {
                        dialog.infoBasis = data.info_basis;
                        dialog.exceptionMsg = data.info_basis[0].Exception;
                        dialog.currentItemID = data.info_basis[0].SendID; // 預設請求第一筆
                        $MMWService.sendToServer({
                            uri: 'ServicesSTD.Module_WIP.warehouse_fail_eaiqueue_info_get',
                                // $mddProvider.Getfunc('B0401_StorageException', 'warehouse_fail_eaiqueue_info_get'),
                            content: {
                                Info_Flag: "Data",
                                StockIn_Type: 0,
                                Send_ID: dialog.infoBasis[0].SendID
                            },
                            success: function (data) {
                                dialog.infoDetail = data.info_detail;
                            },
                        });
                    },
                });

                dialog.getPage = function(data, filter){
                    // 20220422 modify by Alan for #102658	 :  [sMES 研發組(標準產品)] : 入庫單拋轉失敗可重新拋轉機制
                    // 當後傳回null時會被$filter過濾掉，因此將filter值重設undefined
                    for(key in filter) {
                        if (filter[key] === '') {
                            filter[key] = undefined;
                        }
                    }
                    return $filter("filter")(data, filter)
                }

                dialog.getInfoDetail = function(item){
                    // 20220422 modify by Alan for #102658	 :  [sMES 研發組(標準產品)] : 入庫單拋轉失敗可重新拋轉機制
                    // 避免點擊同項目時重複請求
                    if (dialog.currentItemID != item.SendID) {
                        dialog.exceptionMsg = item.Exception;
                        dialog.currentItemID = item.SendID;
                        $MMWService.sendToServer({
                            uri: 'ServicesSTD.Module_WIP.warehouse_fail_eaiqueue_info_get',
                                // $mddProvider.Getfunc('B0401_StorageException', 'warehouse_fail_eaiqueue_info_get'),
                            content: {
                                Info_Flag: "Data",
                                StockIn_Type: 0,
                                Send_ID: dialog.currentItemID
                            },
                            success: function (data) {
                                dialog.infoDetail = data.info_detail;
                            },
                        });
                    }
                }

                dialog.back = function(){
                    dialog.hide();
                };
                
                dialog._event = {
                    'dialog.infoBasis': {
                        rowClick: (item, object) => {
                            dialog.getInfoDetail(item);
                        }
                    }
                }

                return dialog;
            }

            //20221014 add by 翰鴻 for M#117105
            $scope.serialNoCheck = function (item) {                
                if (item.DEFAULTVALUE != null) {
                    item.DEFAULTVALUE = item.DEFAULTVALUE.toLowerCase();
                }
                $mdDialog.dialog(
                    'module/moduleB/program/B04/B0401/B0401_Pick.html',
                    function (dialog) {
                        return {
                            css_url: 'module/moduleB/program/B04/B0401/B0401_Pick.css',
                            serialData: item,
                            notInWarehouse: item.notInWarehouse,
                            selectList: item.selectList,
                            onlyScan: item.DEFAULTVALUE === 'only scan',
                            clickUnselectItem: function (SI, index) {
                                dialog.selectList.push(SI);
                                dialog.notInWarehouse.splice(index, 1);
                            },
                            clickselectItem: function (SI, index) {
                                dialog.selectList.splice(index, 1);
                                dialog.notInWarehouse.push(SI);
                            },
                            // 20231228 add by Alan for #153945	 : 全選/全不選
                            clickUnselectItemAll: function () {
                                dialog.selectList = dialog.selectList.concat(dialog.notInWarehouse);
                                dialog.notInWarehouse = [];
                            },
                            clickSelectItemAll: function () {
                                dialog.notInWarehouse = dialog.notInWarehouse.concat(dialog.selectList);
                                dialog.selectList = [];
                            },
                            qrcode_plot_no: function () {
                                console.log("qrcode_plot_no");
                                $scope.$root.OpenScanner({
                                    after: function (result) {
                                        judgingData(result.text);
                                    },
                                    exception: function () {
                                        //目前裝置無法使用相機
                                        $scope.$root.showAlert($filter('translate')('B0214.showAlert.column3'));
                                    },
                                    orientation: 'landscape'
                                });
                            },
                            qrcode_scan: function (event) {
                                if (event.key.toLowerCase() == "enter") {
                                    dialog.judgingData(dialog.qrcode);
                                    dialog.qrcode = '';
                                }
                            },
                            judgingData: function (data) {
                                var existList = $.grep(dialog.notInWarehouse, function (n, i) {
                                    return n.PCSNo == data
                                });
                                console.log(existList);
                                if (existList.length > 0) {
                                    dialog.selectList.push(existList[0]);
                                    var index = dialog.notInWarehouse.indexOf(existList[0]);
                                    dialog.notInWarehouse.splice(index, 1);
                                }
                                else {
                                    var existList2 = $.grep(dialog.selectList, function (n, i) {
                                        return n.PCSNo == data
                                    });
                                    console.log(existList2);
                                    if (existList2.length > 0) {
                                        dialog.notInWarehouse.push(existList2[0]);
                                        var index2 = dialog.selectList.indexOf(existList2[0]);
                                        dialog.selectList.splice(index2, 1);
                                    }
                                    else {
                                        //成品序號：XXXX，不存在或已經入庫!!
                                        $scope.$root.showAlert($filter('translate')('B0401.msg.not_exists', { serialno: data }));
                                    }
                                }
                            },
                            back: function () {
                                item.notInWarehouse = dialog.notInWarehouse;
                                item.selectList = dialog.selectList;
                                item.serialNo_qty = item.selectList.length;
                                dialog.hide();
                            },
                            confirm: function () {
                                item.notInWarehouse = dialog.notInWarehouse;
                                item.selectList = dialog.selectList;
                                item.serialNo_qty = item.selectList.length;
                                dialog.hide();
                            },
                            beforeShown: function () {
                                if (!dialog.selectList) dialog.selectList = new Array();
                                $("#qrcode").focus();
                            }
                        }
                    }
                )
            }

            // 20221004 modify by Alan for #112097	 :  送驗開窗
            // 20221011 modify by Alan for #112097	 :  合併世穎提供的代碼
            $scope.sendFQC = function(item) {
                $mddProvider.UseForm('B0401_sendFQC', () =>{
                    $mdDialog.dialog(
                        'module/moduleB/program/B04/B0401/B0401_sendFQC.tmp.html',
                        function(dialog) {
                            return {
                                css_url:'module/moduleB/program/B04/B0401/B0401.css',
                                _event: {
                                    availableQCQty: {
                                        isDisabled: 'Y'                                        
                                    },
                                    type: {
                                        click: (type, object) => {
                                            dialog.changeType(type);
                                        }
                                    }
                                },
                                _fn: {
                                    Execute: {
                                        click: () => {
                                            dialog.confirm();
                                        }
                                    }
                                },
                                type: 'sendQC',
                                prodQty: item.qty,
                                finalQty: item.FinalQTY,
                                availableQCQty: 0,
                                QCQty: 0,
                                QcType:1,
                                notInWarehouse: [],
                                selectList: [],
                                allpcsnodatail:[],
                                showpcsno:'false',
                                beforeShown: function () {
                                    // 送驗 => 生產數量(prodQty)
                                    // 重新送驗 => 最終數量(finalQty)
                                    // 預設選擇送驗並代入生產數量(prodQty)
                                    dialog.availableQCQty = dialog.prodQty;
                                    dialog.QCQty = dialog.prodQty;
                                    //ADD BY H-18451  20230524 FOR #119055 获取做過序號收集的结果
                                    $MMWService.sendToServer({
                                        uri: $mddProvider.Getfunc('B0401_sendFQC', 'Warehouse_getpcsno_info_get'),
                                        //uri: ServicesSTD.Module_WIP.Warehouse_getpcsno_info_get,
                                        content: { plot_no: item.plot_no },
                                        success: function (response) {
                                          
                                            if (response.pCSNODetails.length > 0) {
                                                dialog.notInWarehouse = response.pCSNODetails;
                                                dialog.allpcsnodatail = response.pCSNODetails;
                                                dialog.showpcsno = 'true';
                                                dialog.QCQty = 0;
                                            }
                                        },
                                    });
                                },
                                clickUnselectItem: function (SI, index) {
                                    dialog.selectList.push(SI);
                                    dialog.notInWarehouse.splice(index, 1);
                                    dialog.QCQty = dialog.selectList.length;
                                },
                                clickselectItem: function (SI, index) {
                                    dialog.selectList.splice(index, 1);
                                    dialog.notInWarehouse.push(SI);
                                    //ADD BY H-18451  20230524 FOR #119055 送检数量
                                    dialog.QCQty = dialog.selectList.length;
                                },
                                qrcode_plot_no: function () {
                                    console.log("qrcode_plot_no");
                                    $scope.$root.OpenScanner({
                                        after: function (result) {
                                            judgingData(result.text);
                                        },
                                        exception: function () {
                                            //目前裝置無法使用相機
                                            $scope.$root.showAlert($filter('translate')('B0214.showAlert.column3'));
                                        },
                                        orientation: 'landscape'
                                    });
                                },
                                qrcode_scan: function (event) {
                                    if (event.key.toLowerCase() == "enter") {
                                        dialog.judgingData(dialog.qrcode);
                                        dialog.qrcode = '';
                                    }
                                },
                                judgingData: function (data) {
                                    var existList = $.grep(dialog.notInWarehouse, function (n, i) {
                                        return n.PCSNo == data
                                    });
                                    console.log(existList);
                                    if (existList.length > 0) {
                                        dialog.selectList.push(existList[0]);
                                        var index = dialog.notInWarehouse.indexOf(existList[0]);
                                        dialog.notInWarehouse.splice(index, 1);
                                    }
                                    else {
                                        var existList2 = $.grep(dialog.selectList, function (n, i) {
                                            return n.PCSNo == data
                                        });
                                        console.log(existList2);
                                        if (existList2.length > 0) {
                                            dialog.notInWarehouse.push(existList2[0]);
                                            var index2 = dialog.selectList.indexOf(existList2[0]);
                                            dialog.selectList.splice(index2, 1);
                                        }
                                        else {
                                            //成品序號：XXXX，不存在或已經入庫!!
                                            $scope.$root.showAlert($filter('translate')('B0401.msg.not_exists', { serialno: data }));
                                        }
                                    }
                                },
                                back: function() {
                                    dialog.hide();
                                },
                                confirm: function() {
                                    if(dialog.QCQty <= 0) {
                                        return;
                                    }
                                    if((+dialog.QCQty) > (+dialog.availableQCQty)) {
                                        let msg = dialog.type === 'sendQC' 
                                            ? 'B0401_FQC.msg.sendQty_biggerthan_prodQty' 
                                            : 'B0401_FQC.msg.reSendQty_biggerthan_finalQty';
                                        $scope.$root.showAlert($filter('translate')(msg))
                                        return;
                                    }
                                    var content = {
                                        mo_no: item.wo_no,
                                        plot_no: item.plot_no,
                                        op_no: item.op_no,
                                        product_no: item.item_no,
                                        product_version: item.item_ver,
                                        qty: dialog.QCQty,
                                        QcType:dialog.QcType,
                                        InventoryNo: item.inventoryno || '',
                                        do_flag: String(item.DOFlag),
                                        //ADD BY H-18451  20230524 FOR #119055 是否显示控件
                                        showpcsno: dialog.showpcsno,
                                        //ADD BY H-18451  20230524 FOR #119055 『準備檢驗』中的成品序號
                                        selectList: dialog.selectList,
                                        mes_inventoryNo:item.mes_inventoryNo

                                    }
                                    
                                    $MMWService.sendToServer({
                                        uri: 'ServicesSTD.Module_WIP.Warehouse_Need_FQC_Process',
                                            // $mddProvider.Getfunc('B0401_sendFQC','Warehouse_Need_FQC_Process'),
                                        content: content,
                                        success: function (response) {
                                            $scope.search();
                                            // 2022-10-13 #0112097 FQC 提示信息 start
                                            if(response.qc_no) {
                                                $scope.$root.showToast($filter('translate')('B0401_FQC.msg.inspect_list_has_been_created', { qc_no: response.qc_no }), 10);
                                            }
                                            // 2022-10-13 #0112097 FQC 提示信息，僅調整數量 start
                                        },
                                    });

                                    dialog.hide();
                                },
                                changeType: function(type) {
                                    dialog.type = type;
                                    if(dialog.type === 'sendQC') {
                                        dialog.availableQCQty = dialog.prodQty;
                                        dialog.QCQty = dialog.prodQty;
                                        dialog.QcType = 1;
                                    } else {
                                        dialog.availableQCQty = dialog.finalQty;
                                        dialog.QCQty = dialog.finalQty;
                                        dialog.QcType = 2;
                                    }
                                }
                            }
                        }
                    )
                })
            }

            // 20221004 modify by Alan for #112097	 :  檢驗單開窗
            $scope.showInspectionList = function(item) {
                $mddProvider.UseForm('B0401_InspectionList', () =>{
                    $mdDialog.dialog(
                        'module/moduleB/program/B04/B0401/B0401_InspectionList.tmp.html',
                        function(dialog) {
                            let dialogScope = dialog.getDialogScope();
                            //dialogScope.codeList = [
                            //    {name:$filter('translate')('B0401_inspectList.column.qcform_no'), column_name:'qcform_no'},
                            //    {name:$filter('translate')('B0401_inspectList.column.user_no'), column_name:'user_no'},
                            //    {name:$filter('translate')('B0401_inspectList.column.record_date'), column_name:'record_date',
                            //        value_s:new Date(), value_e:new Date(), data_type:'SE'},
                            //    {name:$filter('translate')('B0401_inspectList.column.qc_user_no'), column_name:'qc_user_no'},
                            //    {name:$filter('translate')('B0401_inspectList.column.qc_date'), column_name:'qc_date',
                            //        value_s:new Date(), value_e:new Date(), data_type:'SE'},
                            //    {name:$filter('translate')('B0401_inspectList.column.qc_result_type'), column_name:'qc_result_type'},
                            //];
                            // 複寫預設beforeSearch方法
                            dialogScope.$watch('beforeSearch', (newVal, oldVal) => {
                                if(newVal && typeof newVal === 'function' && newVal.toString() != dialogScope.search.toString()) {
                                    dialogScope.beforeSearch = dialogScope.search;
                                }
                            })
                            // 複寫預設search方法
                            dialogScope.search = () => {
                                const content = {
                                    lot_no: item.plot_no, // required
                                    op_no: item.op_no, // required
                                    record_date_starts: "",
                                    record_date_ends: "",
                                    qc_date_starts: "",
                                    qc_date_ends: "",
                                    user_no: "",
                                    qc_user_no: "",
                                    qcform_no: "",
                                    qc_result_type: "",
                                };
                                let conditionList = $rootScope.genConditioninfo();
                                conditionList.forEach((condition) => {
                                    if(condition.column_name === 'record_date' || condition.column_name === 'qc_date'){
                                        if(condition.query_mode === 4) {
                                            content[condition.column_name + '_starts'] = condition.value;
                                        } else {
                                            content[condition.column_name + '_ends'] = condition.value;
                                        }
                                    } else {
                                        content[condition.column_name] = condition.value;
                                    }
                                })

                                $MMWService.sendToServer({
                                    uri: 'ServicesSTD.Module_WIP.fqc_qcform_data_get',
                                        // $mddProvider.Getfunc('B0401_InspectionList', 'fqc_qcform_data_get'),
                                    content: content,
                                    success: function (data) {
                                        // 20230627 by  shiwl 0138723: 东声电子：FQC送检，检验完成后在入库作业页面点击查询检验单数据没有显示出来
                                        dialog.fqc_qcform_details = data.fqc_qcform_details;
                                    },
                                });
                            }

                            return {
                                PageConfig: { page: 0, page_count: 25 },
                                back: function() {
                                    dialog.hide();
                                },
                            }
                        }
                    )
                })
            }
            
            // 20221024 modify by Alan for #109844	 :  回收
            $scope.openRollBackDialog = function(item){
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.warehouse_rollback_info_get',
                        // $mddProvider.Getfunc('B0401', 'warehouse_rollback_info_get'),
                    content: {
                        plot_no: item.plot_no,
                        item_no : item.item_no,
                        mes_inventoryNo :item.mes_inventoryNo,
                        op_no : item.op_no
                    },
                    success: function (data) {   
                        $mddProvider.UseForm('B0401_RollBack', () =>{  
                            $mdDialog.dialog(
                                'module/moduleB/program/B04/B0401/B0401_RollBack.html',
                                function (dialog) {
                                    return {
                                        //dialog._fn['Execute'].click('Execute');
                                        _fn: {
                                            Execute: {
                                                click: () => {
                                                    dialog.confirm();
                                                }
                                            }
                                        },
                                        css_url:'JSplugins/angular-material-lite/template/dynamicService.tmp.css',
                                        plot_info_detail : data.details,
                                        back: function () {
                                            dialog.hide();
                                        },
                                        itemCheck : function(index,item){                                        
                                            if(item.checked){
                                                item.checked = !item.checked;
                                            }else{
                                                dialog.plot_info_detail.forEach(function(detail){
                                                    detail.checked = false;
                                                })
                                                item.checked = true;
                                            }
                                        },
                                        confirm: function () {
                                            dialog.plot_info_detail.forEach(function(detail){
                                                if(detail.checked){
                                                    detail.item_no = item.item_no;
                                                    detail.item_ver = item.item_ver;
                                                    detail.inventoryno = item.mes_inventoryNo;
                                                    $MMWService.sendToServer({
                                                        uri: 'ServicesSTD.Module_WIP.warehouse_rollback_process',
                                                            // $mddProvider.Getfunc('B0401_RollBack','warehouse_rollback_process'),
                                                        content: {
                                                            plot_info_detail: detail
                                                        },
                                                        success: function (data) {  
                                                            dialog.hide();
                                                            $scope.$root.showToast($filter('translate')('B0401.msg.process_success'), 10);
                                                            $scope.search();
                                                        }
                                                    })
                                                }
                                            })
                                        
                                        }
                                    }
                                }
                            )
                        })                
                    }
                });
            }    
        }
    ];
});
